﻿using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Attributes;
using ZhonTai.Admin.Tools.Cache;
using ZhonTai.Industry.Contracts.Core.Enums;
using ZhonTai.Industry.Contracts.Core.Model;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.ReworkDefectRecord;
using ZhonTai.Industry.Domain.WorkParamRecord;
using ZhonTai.Industry.Domain.WorkStationRecord;

namespace ZhonTai.Industry.Removable.CraftGather.Save
{
    /// <summary>
    /// 保存操作
    /// </summary>
    [InjectTransient]
    public class SaveHandle : WorkExecuteBase
    {
        private readonly ICacheTool _cacheTool;
        private readonly IWorkParamRecordRepository _workParamRecordRepository;
        private readonly IWorkStationRecordRepository _stationRecordRepository;
        private readonly IReworkDefectRecordRepository _reworkDefectRecordRepository;

        public SaveHandle(
            ICacheTool cacheTool,
            IWorkParamRecordRepository workParamRecordRepository,
            IWorkStationRecordRepository stationRecordRepository,
            IReworkDefectRecordRepository reworkDefectRecordRepository)
        {
            _cacheTool = cacheTool;
            _stationRecordRepository = stationRecordRepository;
            _workParamRecordRepository = workParamRecordRepository;
            _reworkDefectRecordRepository = reworkDefectRecordRepository;
        }

        public override async Task ExecuteAsync(PushContent content)
        {
            try
            {
                //保存主条码
                string? masterCode = content.Plc.GetValue<string>(OffsetConsts.SaveMasterCode);
                if (string.IsNullOrWhiteSpace(masterCode))
                {
                    var otherResult = await content.Plc.WriteValueAsync(2, (short)SaveResultEnum.EmptyMasterCode);
                    if (otherResult.IsSuccess)
                    {
                        logger.Warn($"查询请求：工站【{content.OPCode}】条码不存在，回复【{SaveResultEnum.EmptyMasterCode}】写入成功！");
                    }
                    return;
                }
                //开始时间
                DateTime startTime = await _cacheTool.GetAsync<DateTime>(CacheKey.QueryStartTime + content.StationId);
                if (startTime == DateTime.MinValue)
                {
                    startTime = DateTime.Now;
                }
                string? stationCode = content.OPCode;
                //工站ID
                long stationId = content.StationId;
                //订单ID
                long? orderId = await _cacheTool.GetAsync<long?>(CacheKey.StationId);
                //产品ID
                long? productId = await _cacheTool.GetAsync<long?>(CacheKey.ProductId);
                //产品总状态
                short productStatus = content.Plc.GetValue<short>(OffsetConsts.ProductStatus);
                //载体
                string? slot = content.Plc.GetValue<string?>(OffsetConsts.Slot);
                //缺陷代码
                string? defectCode = content.Plc.GetValue<string?>(OffsetConsts.DefectCode);
                List<DBField> param = content.Plc.PLCDB.DataFields.FindAll(f => f.GroupName == "Param");
                if (param.Count > 0)
                {
                    List<WorkParamRecordEntity> workParamList = new(param.Count);
                    //保存工艺参数
                    List<WorkParamRecordEntity>? workParamRecords = param.Select(field => new WorkParamRecordEntity
                    {
                        ProductCode = masterCode,
                        StationId = stationId,
                        OrderId = orderId,
                        ProductModelId = productId,
                        ParameterName = field.Description,
                        ParameterValue = content.Plc.GetValue<string>(field.Another),
                        Unit = field.Unit,
                        UpperLimit = field.Upper,
                        LowerLimit = field.Lower,
                        Status = productStatus == 1 ? "OK" : "NG",
                        Upload = false
                    }).ToList();
                    workParamList.AddRange(workParamRecords);
                    await _workParamRecordRepository.InsertAsync(workParamList);
                }
                //保存过站信息
                var stationRecordEntity = new WorkStationRecordEntity
                {
                    ProductCode = masterCode,
                    StationId = stationId,
                    OrderId = orderId,
                    ProductModelId = productId,
                    ShiftId = 1,
                    StartTime = startTime,
                    EndTime = DateTime.Now,
                    CycleTime = (DateTime.Now - startTime).TotalSeconds,
                    Result = productStatus == 1 ? "OK" : "NG",
                    Slot = slot,
                    DefectCode = productStatus == 1 ? null : defectCode
                };
                //记录NG产品
                if (productStatus != (short)1)
                {
                    var reworkDefectRecordEntity = new ReworkDefectRecordEntity
                    {
                        ProductCode = masterCode,
                        DefectCode = defectCode == null ? null : defectCode,
                        FirstStationId = stationId,
                        FristStationCode = stationCode,
                        CurrentStatus = 1,
                        DetectionDate = DateTime.Now,
                    };
                    await _reworkDefectRecordRepository.InsertAsync(reworkDefectRecordEntity);
                }
                await _stationRecordRepository.InsertAsync(stationRecordEntity);
                var result = await content.Plc.WriteValueAsync(2, (short)SaveResultEnum.Success);
                if (result.IsSuccess)
                {
                    logger.Info($"保存请求：条码：【{masterCode}】工站【{content.OPCode}】回复【{SaveResultEnum.Success}】写入成功!");
                }
            }
            catch (Exception ex)
            {
                var result = await content.Plc.WriteValueAsync(2, (short)SaveResultEnum.Abnormal);
                if (result.IsSuccess)
                {
                    logger.Error($"保存请求：工站【{content.OPCode}】程序保存错误，原因：{ex.Message},回复【{SaveResultEnum.Abnormal}】成功!");
                }
            }
        }
    }
}